<template>
  <div>
    <a-modal title="修改资料" :visible="showVisible" width="800px" @cancel="handleCancel" @ok="handleOK">
      <a-form
          class="edit-form"
          :model="formState"
          name="basic"
          :ref="formRef"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 8}"
          autocomplete="off"
          @finish="onFinish"
          :rules="formRules"
          @finishFailed="onFinishFailed">
        <a-form-item
            label="昵称"
            name="userNick">
          <a-input v-model:value="formState.userNick"/>
        </a-form-item>
        <a-form-item
            label="账号"
            name="userName">
          <a-input v-model:value="formState.userName"/>
        </a-form-item>
        <a-form-item
            label="电话"
            name="userTel">
          <a-input v-model:value="formState.userTel"/>
        </a-form-item>
        <a-form-item
            label="邮箱"
            name="userEmail">
          <a-input v-model:value="formState.userEmail"/>
        </a-form-item>
        <a-form-item
            label="身份证"
            name="userIdCard">
          <a-input v-model:value="formState.userIdCard"/>
        </a-form-item>
        <a-form-item
            label="年龄"
            name="userAge">
          <a-input v-model:value="formState.userAge"/>
        </a-form-item>
        <a-form-item
            label="详细地址"
            name="userAddress">
          <a-input v-model:value="formState.userAddress"/>
        </a-form-item>
        <a-form-item
            label="性别"
            name="userSex">
          <a-input v-model:value="formState.userSex"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {computed, reactive, ref} from "vue";
import {useStore} from "vuex";
import {message} from "ant-design-vue";

export default {
  name: "editUserInfo",
  props: ['showVisible'],
  data() {
    return {}
  },
  methods: {
    handleCancel() {
      this.$emit("closeEditUserInfo")
    },
    handleOK() {
      this.checkEditForm().then(() => {
        //发起请求进行修改
        if (this.oldInfo == this.formState) {
          //代表值都相等
          alert("值未修改 不做处理")
          this.$emit("closeEditUserInfo")
        } else {
          this.$httpPost("/xy/user/editUserInfo", this.formState).then(res => {
            if (res.data.code == 500) {
              message.error(res.data.msg)
            }
            this.$emit("closeEditUserInfo")
          })
        }
      })
    },
    copyUserInfoToForm() {
      this.formState.userId = this.userinfo.userId
      this.formState.userNick = this.userinfo.userNick
      this.formState.userName = this.userinfo.userName
      this.formState.userTel = this.userinfo.userTel
      this.formState.userEmail = this.userinfo.userEmail
      this.formState.userIdCard = this.userinfo.userIdCard
      this.formState.userAge = this.userinfo.userAge
      this.formState.userAddress = this.userinfo.userAddress
      this.formState.userSex = this.userinfo.userSex
      this.oldInfo.userId = this.userinfo.userId
      this.oldInfo.userNick = this.userinfo.userNick
      this.oldInfo.userName = this.userinfo.userName
      this.oldInfo.userTel = this.userinfo.userTel
      this.oldInfo.userEmail = this.userinfo.userEmail
      this.oldInfo.userIdCard = this.userinfo.userIdCard
      this.oldInfo.userAge = this.userinfo.userAge
      this.oldInfo.userAddress = this.userinfo.userAddress
      this.oldInfo.userSex = this.userinfo.userSex
    }
  },
  mounted() {
    this.copyUserInfoToForm()
  },
  setup() {
    const oldInfo = reactive({
      userId: '',
      userNick: '',
      userName: '',
      userTel: '',
      userEmail: '',
      userIdCard: '',
      userAge: '',
      userAddress: '',
      userSex: ''
    })
    const formRef = ref();
    const checkEditForm = async () => {
      try {
        return await formRef.value.validateFields()
      } catch (errorInfo) {
        return errorInfo
      }
    };
    const formState = reactive({
      userId: '',
      userNick: '',
      userName: '',
      userTel: '',
      userEmail: '',
      userIdCard: '',
      userAge: '',
      userAddress: '',
      userSex: ''
    });
    const onFinish = values => {
      console.log('Success:', values);
    };
    const onFinishFailed = errorInfo => {
      console.log('Failed:', errorInfo);
    };
    let userNickVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入昵称:');
      } else {
        if (value.length > 10) {
          return Promise.reject('昵称长度只能在1-10之间！');
        }
        return Promise.resolve();
      }
    };
    let userNameVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入账号:');
      } else {
        if (value.length < 5 || value.length > 10) {
          return Promise.reject('账号长度只能在1-10之间！');
        }

        return Promise.resolve();
      }
    };

    let userAgeVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('年龄不能为空:');
      } else {
        if (value < 0 || value.length > 3) {
          return Promise.reject('年龄格式不规范,请重新输入！');
        }
        return Promise.resolve();
      }
    };
    let userSexValid = async (_rule, value) => {
      console.log(value)
      if (value === '') {
        return Promise.reject('性别不能为空:');
      } else {
        if (value == '男' || value == '女') {
          return Promise.resolve();
        } else {
          return Promise.reject("性别只能填男或者女")
        }
      }
    };
    let userTelValid = async (_rule, value) => {
      let phoneReg = /(^1\d{10}$)|(^[0-9]\d{7}$)/;
      if (!phoneReg.test(value)) {
        return Promise.reject('电话号码格式错误');
      } else {
        return Promise.resolve();
      }
    };
    let userEmailValid = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入邮箱');
      } else {
        const szReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
        if (!szReg.test(value)) {
          message.error("请输入正确的邮箱")
        }
        if (formState.useremail !== '') {
          await formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    };
    let userIdCardValid = async (_rule, value) => {
      let idCardReg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;
      if (!idCardReg.test(value)) {
        return Promise.reject('身份证号码格式错误');
      } else {
        return Promise.resolve();
      }
    }
    let userAddressValid = async (_rule, value) => {
      if (value.length > 50) {
        return Promise.reject('地址过长');
      } else {
        return Promise.resolve();
      }
    }
    const formRules = reactive({
      userNick: [{
        required: true,
        validator: userNickVaild,
        trigger: 'change',
      }],
      userName: [{
        required: true,
        validator: userNameVaild,
        trigger: 'change',
      }],
      userTel: [{
        required: true,
        validator: userTelValid,
        trigger: 'change',
      }],
      userEmail: [{
        required: true,
        validator: userEmailValid,
        trigger: 'change',
      }],
      userIdCard: [{
        required: true,
        validator: userIdCardValid,
        trigger: 'change',
      }],
      userAge: [{
        required: true,
        validator: userAgeVaild,
        trigger: 'change',
      }],
      userSex: [{
        required: true,
        validator: userSexValid,
        trigger: 'change',
      }],
      userAddress: [{
        required: true,
        validator: userAddressValid,
        trigger: 'change',
      }],
    })
    let store = useStore();
    return {
      oldInfo,
      checkEditForm,
      formState,
      formRef,
      onFinish,
      formRules,
      onFinishFailed,
      token: computed(() => {
        return store.getters.getToken
      }),
      userinfo: computed(() => {
        return store.getters.getUser
      })
    }
  }
}
</script>

<style scoped>
.edit-form {
}
</style>